package com.cgtong.android.activity;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.cgtong.android.App;
import com.cgtong.android.R;
import com.cgtong.android.adapter.ProblemDetailPictureAdapter;
import com.cgtong.android.adapter.VerticalStepAdapter;
import com.cgtong.android.base.BaseTitleActivity;
import com.cgtong.android.bean.ProblemBean;
import com.cgtong.android.bean.SimpleResult;
import com.cgtong.android.callback.ErrorCallback;
import com.cgtong.android.event.GetUserEvent;
import com.cgtong.android.http.ConstantManager;
import com.cgtong.android.mvp.contract.ProblemDetailContract;
import com.cgtong.android.mvp.presenter.ProblemDetailPresenter;
import com.cgtong.android.util.CommonUtils;
import com.cgtong.android.util.PostUtil;
import com.cgtong.android.widget.BaseDialog;
import com.cgtong.android.widget.audio.AudioPlayManager;
import com.cgtong.android.widget.audio.IAudioPlayListener;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.zhouyou.http.EasyHttp;
import com.zhouyou.http.callback.DownloadProgressCallBack;
import com.zhouyou.http.exception.ApiException;
import com.zhouyou.http.model.ApiResult;

import org.simple.eventbus.EventBus;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * 大家看看详情页
 */
public class ProblemDetailActivity extends BaseTitleActivity implements ProblemDetailContract.View {

    public static final String TAG = ProblemDetailActivity.class.getSimpleName();
    private static final String KEY_PROBLEM_ID = "problem_id";
    private static final String KEY_CAN_DELETE = "can_delete";
    private static final String KEY_CAN_EVALAUTE = "can_evaluate";

    public static final String KEY_LIST_ITEM_POSITION = "followed_problem_position";
    public static final String KEY_LIST_ITEM_ID_POSITION = "followed_problem_id_position";


    public static final int KEY_CODE_FOLLOW_PROBLEM = 333;
    public static final int KEY_CODE_REPORT_PROBLEM = 444;

    @BindView(R.id.avatar_img)
    CircleImageView mAvatarImg;
    @BindView(R.id.name_txt)
    TextView mNameTxt;
    @BindView(R.id.date_txt)
    TextView mDateTxt;
    @BindView(R.id.follow_file_txt)
    TextView mFollowFileTxt;
    @BindView(R.id.grid_view)
    GridView mGridView;
    @BindView(R.id.content_txt)
    TextView mContentTxt;
    @BindView(R.id.step_recycler_view)
    RecyclerView mStepRecyclerView;
    @BindView(R.id.location_txt)
    TextView mLocationTxt;
    @BindView(R.id.play_audio_img)
    ImageView mPlayAudioImg;
    @BindView(R.id.audio_ll)
    LinearLayout mAudioLl;

    @BindView(R.id.evaluate_txt)
    TextView mEvaluateTxt;
    @BindView(R.id.evaluate_ll)
    LinearLayout mEvaluateLl;
    @BindView(R.id.very_satisfied_img)
    ImageView mVerySatisfiedImg;
    @BindView(R.id.very_satisfied_ll)
    LinearLayout mVerySatisfiedLl;
    @BindView(R.id.satisfied_img)
    ImageView mSatisfiedImg;
    @BindView(R.id.satisfied_ll)
    LinearLayout mSatisfiedLl;
    @BindView(R.id.basically_satisfied_img)
    ImageView mBasicallySatisfiedImg;
    @BindView(R.id.basically_satisfied_ll)
    LinearLayout mBasicallySatisfiedLl;
    @BindView(R.id.dissatisfied_img)
    ImageView mDissatisfiedImg;
    @BindView(R.id.dissatisfied_ll)
    LinearLayout mDissatisfiedLl;
    @BindView(R.id.step_fl)
    FrameLayout mStepFl;
    @BindView(R.id.play_audio_duration_txt)
    TextView mAudioDurationTxt;

    private ProblemDetailContract.Presenter mPresenter;
    private ProblemBean mProblemBean;
    private long mProblemId;
    private int mEvaluateLevel = 0;//评价 0,未评价，1，很满意，2，满意，3，普通，4不满意

    private int mPosition;//我关注的案卷列表进入详情，带入的position

    private boolean mFollowedProblem = true;//标记已经关注该案卷
    private boolean mCanDelete;//4,已结案,5已评价,7,未上报
    private boolean mCanEvaluate;//4,已结案，5已评价


    public static void start(Context context, long problemId, boolean canDelete, boolean canEvaluate) {
        Intent starter = new Intent(context, ProblemDetailActivity.class);
        starter.putExtra(KEY_PROBLEM_ID, problemId);
        starter.putExtra(KEY_CAN_DELETE, canDelete);
        starter.putExtra(KEY_CAN_EVALAUTE, canEvaluate);
        Log.d(TAG, "能否删除：" + canDelete + " 能否评价：" + canEvaluate);
        context.startActivity(starter);
    }

    public static void startForResult(Activity activity, long problemId, boolean canDelete, boolean canEvaluate, int position) {
        Intent starter = new Intent(activity, ProblemDetailActivity.class);
        starter.putExtra(KEY_PROBLEM_ID, problemId);
        starter.putExtra(KEY_CAN_DELETE, canDelete);
        starter.putExtra(KEY_CAN_EVALAUTE, canEvaluate);
        starter.putExtra(KEY_LIST_ITEM_POSITION, position);
        activity.startActivityForResult(starter, KEY_CODE_REPORT_PROBLEM);
    }

    public static void startForResult(Fragment fragment, long problemId, boolean canDelete, boolean canEvaluate, int position) {
        Intent starter = new Intent(fragment.getActivity(), ProblemDetailActivity.class);
        starter.putExtra(KEY_PROBLEM_ID, problemId);
        starter.putExtra(KEY_CAN_DELETE, canDelete);
        starter.putExtra(KEY_CAN_EVALAUTE, canEvaluate);
        starter.putExtra(KEY_LIST_ITEM_POSITION, position);
        fragment.startActivityForResult(starter, KEY_CODE_FOLLOW_PROBLEM);
    }


    @Override
    protected String getContentTitle() {
        return getString(R.string.title_txt_detail);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_problem_detail;
    }

    @Override
    protected void loadDataByNet() {
        mProblemId = getIntent().getLongExtra(KEY_PROBLEM_ID, -1);
        mPosition = getIntent().getIntExtra(KEY_LIST_ITEM_POSITION, -1);
        mCanDelete = getIntent().getBooleanExtra(KEY_CAN_DELETE, false);
        mCanEvaluate = getIntent().getBooleanExtra(KEY_CAN_EVALAUTE, false);
        Log.d(TAG, "mProblemId = " + mProblemId + " mPosition = " + mPosition + " mCanDelete = " + mCanDelete + " mCanEvaluate = " + mCanEvaluate);
        if (mProblemId == -1) {
            finish();
            return;
        }

        mPresenter = new ProblemDetailPresenter(this);
        mPresenter.httpProblemDetailData(mProblemId);

        //已完结的问题，显示删除按钮
        //根据修改问题不允许删除gg
        if (mCanDelete) {
            mTitleRightTxt.setVisibility(View.VISIBLE);
            mTitleRightTxt.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(this, R.drawable.ic_delete_problem), null, null, null);
            mTitleRightTxt.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showDeleteDialog();
                }
            });
        }
        //返回监听
        mTitleLeftTxt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(TAG, "onClick:" + mPosition);
                if (!mFollowedProblem) {
                    Intent intent = new Intent();
                    intent.putExtra(KEY_LIST_ITEM_POSITION, mPosition);
                    setResult(RESULT_OK, intent);
                }
                finish();
            }
        });
    }


    /**
     * 是否保存草稿,点击返回弹出
     */
    private void showDeleteDialog() {
        BaseDialog.create(getSupportFragmentManager())
                .setLayoutRes(R.layout.layout_delete_dialog)
                .setViewListener(new BaseDialog.ViewListener() {

                    @Override
                    public void bindView(View view, final Dialog dialog) {
                        TextView okTxt = (TextView) view.findViewById(R.id.delete_txt);
                        okTxt.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mPresenter.deleteReport(mProblemId);
                                dialog.cancel();
                            }
                        });
                        TextView noTxt = (TextView) view.findViewById(R.id.cancel_txt);
                        noTxt.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {

                                dialog.cancel();
                            }
                        });


                    }
                }).setDimAmount(0.3f)
                .setCanCancelable(false).
                setGravity(Gravity.BOTTOM)
                .show();
    }

    @Override
    public void onBackPressed() {
        Log.d(TAG, "mPosition:" + mPosition + " mFollowedProblem:" + mFollowedProblem);
        if (!mFollowedProblem) {
            Intent intent = new Intent();
            intent.putExtra(KEY_LIST_ITEM_POSITION, mPosition);
            setResult(RESULT_OK, intent);
        }
        finish();
    }

    @Override
    protected void onDataReloadByNet(View v) {
        mPresenter.httpProblemDetailData(mProblemId);
    }


    /**
     * 下载语音
     *
     * @param voiceName
     */
    private void downloadVoice(String voiceName) {
        File audioDir = new File(ConstantManager.AUDIO_SAVE_DIR);
        LogUtils.d("audioDir = " + audioDir.getAbsolutePath());
        if (!audioDir.exists()) {
            audioDir.mkdirs();
        }
        EasyHttp.downLoad(mProblemBean.getVoiceUrl())
                .saveName(voiceName)
                .savePath(ConstantManager.AUDIO_SAVE_DIR)
                .execute(new DownloadProgressCallBack<String>() {
                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onError(ApiException e) {
                        ToastUtils.showShort(e.getMessage());
                    }

                    @Override
                    public void update(long bytesRead, long contentLength, boolean done) {

                    }

                    @Override
                    public void onComplete(String path) {

                        LogUtils.d("complete == " + path);
                        playAudio(path);
                    }
                });
    }


    /**
     * 播放语音
     *
     * @param path
     */
    private void playAudio(String path) {
        if (!path.startsWith(ConstantManager.AUDIO_PREFIX)) {
            path = ConstantManager.AUDIO_PREFIX + path;
        }
        LogUtils.d("playAudio == " + path);

        AudioPlayManager.getInstance().stopPlay();//停止播放
        //播放录音
        AudioPlayManager.getInstance().startPlay(this, Uri.parse(String.valueOf(path)), new IAudioPlayListener() {
            @Override
            public void onStart(Uri var1) {
                //开播（一般是开始语音消息动画）
            }

            @Override
            public void onStop(Uri var1) {
                //停播（一般是停止语音消息动画）
            }

            @Override
            public void onComplete(Uri var1) {
                //播完（一般是停止语音消息动画）
            }
        });
    }

    /**
     * 申请读写权限
     */
    private void doDownloadByPermission() {
        RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(new Observer<Boolean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(Boolean aBoolean) {
                        if (aBoolean) {
                            String voiceUrl = mProblemBean.getVoiceUrl();
                            String voiceName = voiceUrl.substring(voiceUrl.lastIndexOf("/") + 1, voiceUrl.length());
                            LogUtils.d("voice name = " + voiceName);
                            String voicePath = ConstantManager.AUDIO_SAVE_DIR + voiceName;
                            LogUtils.d("voice Path == " + voicePath);

                            File voiceFile = new File(voicePath);
                            if (voiceFile.exists()) {
                                playAudio(voicePath);
                            } else {
                                downloadVoice(voiceName);
                            }
                        } else {
                            ToastUtils.showLong(R.string.permission_request_denied);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    @Override
    protected void onPause() {
        super.onPause();
        AudioPlayManager.getInstance().stopPlay();//停止播放

    }

    @Override
    public void onHttpProblemDetailDataSuccess(ProblemBean problemBean) {
        PostUtil.postSuccessDelayed(loadService);
        mProblemBean = problemBean;
        //展示图片
        List<ProblemBean.ResourceBean> picList = problemBean.getResourceList();
        if (picList != null && picList.size() > 0) {
            mGridView.setAdapter(new ProblemDetailPictureAdapter(this, picList));
        } else {
            mGridView.setVisibility(View.GONE);
        }
        //垂直处理步骤
        List<ProblemBean.StatusChangeBean> stepList = problemBean.getStatusChangeList();
        if (stepList != null && stepList.size() > 0) {
            mStepRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
            VerticalStepAdapter verticalStepAdapter = new VerticalStepAdapter(this, stepList, VerticalStepAdapter.Vertical);
            if (mProblemBean.getPushImgList() != null && mProblemBean.getPushImgList().size() > 0) {
                verticalStepAdapter.setPushImageBeanList(mProblemBean.getPushImgList());
            }
            mStepRecyclerView.setAdapter(verticalStepAdapter);
        } else {
            mStepFl.setVisibility(View.GONE);
        }

        mNameTxt.setText(problemBean.getNickName());
        mDateTxt.setText(problemBean.getCreateTime());
        mLocationTxt.setText(problemBean.getAddress());
        //是否关注了该问题，1关注，0未关注
        if (problemBean.getIsAttention() == 1) {
            //已关注
            mFollowFileTxt.setText(getString(R.string.txt_followed_file));
            mFollowFileTxt.setTextColor(ContextCompat.getColor(this, R.color.color_txt_followed_file));
            mFollowFileTxt.setBackgroundDrawable(ContextCompat.getDrawable(this, R.drawable.bg_followed_file));
        } else {
            //未关注
            mFollowFileTxt.setText(getString(R.string.txt_follow_file));
            mFollowFileTxt.setTextColor(ContextCompat.getColor(this, R.color.color_txt_follow_file));
            mFollowFileTxt.setBackgroundDrawable(ContextCompat.getDrawable(this, R.drawable.bg_follow_file));
        }
        //录音
        if (!TextUtils.isEmpty(problemBean.getVoiceUrl())) {
            mAudioLl.setVisibility(View.VISIBLE);
            mAudioDurationTxt.setText(problemBean.getVoiceTime() + "\"");
        } else {
            mAudioLl.setVisibility(View.GONE);
        }
        //描述
        if (!TextUtils.isEmpty(problemBean.getDesc())) {
            mContentTxt.setVisibility(View.VISIBLE);
            mContentTxt.setText(problemBean.getDesc());
        } else {
            mContentTxt.setVisibility(View.GONE);
        }
        if (problemBean.getAvasterId() >= 1 && problemBean.getAvasterId() <= 12) {
            CommonUtils.setUserAvatar(this, mAvatarImg, problemBean.getAvasterId());
        } else {
            LogUtils.d("avatarId错误");
            mAvatarImg.setImageResource(R.drawable.head_1);
        }

        //已经完结
        if (mCanEvaluate) {
            //评价
            if (App.getInstance().getCurrentAccount() != null) {
                if (App.getInstance().isOwnself(problemBean.getCreateUserId())) {
                    mEvaluateLl.setVisibility(View.VISIBLE);
                    if (mProblemBean.getReviewLevel() == 0) {//未评价
                        mEvaluateTxt.setVisibility(View.VISIBLE);
                    } else {
                        //已评价
                        setEvaluatedLevelBg(mProblemBean.getReviewLevel());
                        mVerySatisfiedLl.setEnabled(false);
                        mSatisfiedLl.setEnabled(false);
                        mBasicallySatisfiedLl.setEnabled(false);
                        mDissatisfiedLl.setEnabled(false);
                    }
                }
            }
        }
    }

    private void setEvaluatedLevelBg(int i) {
        LogUtils.d("setEvaluatedLevelBg = " + i);
        mVerySatisfiedImg.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.icon_very_satisfied_gray));
        mSatisfiedImg.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.icon_satisfied_gray));
        mBasicallySatisfiedImg.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.icon_basically_satisfied_gray));
        mDissatisfiedImg.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.icon_dissatisfied_gray));
        if (i == 1) {
            mVerySatisfiedImg.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.icon_very_satisfied));
        } else if (i == 2) {
            mSatisfiedImg.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.icon_satisfied));
        } else if (i == 3) {
            mBasicallySatisfiedImg.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.icon_basically_satisfied));
        } else if (i == 4) {
            mDissatisfiedImg.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.icon_dissatisfied));
        }
    }

    @Override
    public void onError(ApiException e) {
        PostUtil.postCallbackDelayed(loadService, ErrorCallback.class);
    }

    @Override
    public void onError(ProblemBean problemBean) {
        PostUtil.postCallbackDelayed(loadService, ErrorCallback.class);
        ToastUtils.showShort(problemBean.getMsg());
    }

    @Override
    public void onFollowSuccess(long id, ApiResult result) {
        if (result.getCode() == 0) {
            if ("1".equals(result.getMsg())) {
                //关注成功
                mFollowedProblem = true;
                mFollowFileTxt.setText(getString(R.string.txt_followed_file));
                mFollowFileTxt.setTextColor(ContextCompat.getColor(this, R.color.color_txt_followed_file));
                mFollowFileTxt.setBackgroundDrawable(ContextCompat.getDrawable(this, R.drawable.bg_followed_file));

            } else {
                //取消关注成功
                mFollowedProblem = false;
                mFollowFileTxt.setText(getString(R.string.txt_follow_file));
                mFollowFileTxt.setTextColor(ContextCompat.getColor(this, R.color.color_txt_follow_file));
                mFollowFileTxt.setBackgroundDrawable(ContextCompat.getDrawable(this, R.drawable.bg_follow_file));
            }
        } else {
            ToastUtils.showShort(result.getMsg());
        }


    }

    @Override
    public void showLoading(boolean showLoading) {
        if (showLoading) {
            doShowLoading(this, false);
        } else {
            doHideLoading();
        }
    }

    @Override
    public void onEvaluateSuccess(SimpleResult result) {
        if (result.getCode() == 0) {
            mEvaluateTxt.setVisibility(View.GONE);
            //已评价
            setEvaluatedLevelBg(mEvaluateLevel);
            mVerySatisfiedLl.setEnabled(false);
            mSatisfiedLl.setEnabled(false);
            mBasicallySatisfiedLl.setEnabled(false);
            mDissatisfiedLl.setEnabled(false);

            //评价成功后获取用户最新信息（积分）
            EventBus.getDefault().post(new GetUserEvent());
        }
        ToastUtils.showShort(result.getMsg());

    }

    @Override
    public void onDeleteReportSuccess(ApiResult result) {
        if (result.getCode() == 0) {
            if (mPosition != -1) {
                Intent intent = new Intent();
                intent.putExtra(KEY_LIST_ITEM_ID_POSITION, mProblemId);
                setResult(RESULT_OK, intent);
            }
            finish();

        }
        ToastUtils.showShort(result.getMsg());
    }


    @OnClick({R.id.very_satisfied_ll, R.id.satisfied_ll, R.id.basically_satisfied_ll, R.id.dissatisfied_ll, R.id.play_audio_img, R.id.evaluate_txt, R.id.follow_file_txt, R.id.audio_ll
            , R.id.title_left_txt})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_left_txt:
                Log.d(TAG, "onClick:" + mPosition);
                if (!mFollowedProblem) {
                    Intent intent = new Intent();
                    intent.putExtra(KEY_LIST_ITEM_POSITION, mPosition);
                    setResult(RESULT_OK, intent);
                }
                finish();
                break;
            case R.id.very_satisfied_ll:
                mEvaluateLevel = 1;
                setEvaluatedLevelBg(1);
                break;
            case R.id.satisfied_ll:
                mEvaluateLevel = 2;
                setEvaluatedLevelBg(2);

                break;
            case R.id.basically_satisfied_ll:
                mEvaluateLevel = 3;
                setEvaluatedLevelBg(3);
                break;
            case R.id.dissatisfied_ll:
                mEvaluateLevel = 4;
                setEvaluatedLevelBg(4);


                break;
            case R.id.evaluate_txt:
                if (mEvaluateLevel == 0) {
                    ToastUtils.showShort(getString(R.string.txt_unselected_leve));
                    return;
                }
                mPresenter.evaluate(mProblemBean.getId(), mEvaluateLevel);
                break;
            case R.id.play_audio_img:
                doDownloadByPermission();
                break;
            case R.id.follow_file_txt:
                if (((App) getApplicationContext()).isUserLogin()) {
                    mPresenter.follow(mProblemBean.getId());
                } else {
                    Intent intent = new Intent(ProblemDetailActivity.this, LoginActivity.class);
                    startActivityForResult(intent, ConstantManager.REQUEST_LOGIN_CODE);
                }
                break;
            case R.id.audio_ll:
                doDownloadByPermission();
                break;
        }
    }

}
